// 加载Express模块
const express = require('express');

// 加载MySQL模块
const mysql = require('mysql');

// 加载bodyParser模块
const bodyParser = require('body-parser');

// 加载MD5模块
// const md5 = require('md5');


// 加载操作文件模块
var fs = require('fs')

// 创建MySQL连接池
const pool = mysql.createPool({
  host: '127.0.0.1', //MySQL服务器地址
  port: 3306, //MySQL服务器端口号 
  user: 'root', //数据库用户的用户名
  password: '', //数据库用户密码
  database: 'free_room', //数据库名称
  connectionLimit: 20, //最大连接数
  charset: 'utf8' //数据库服务器的编码方式
});

// 创建服务器对象
const app = express();

app.use(bodyParser.urlencoded({
  extended: false
}));


// 加载CORS模块
const cors = require('cors');

// 使用CORS中间件
app.use(cors(
  // {origin: [
  //   // 'http://localhost:8080', 'http://127.0.0.1:8080',
  //   'http://localhost:5500', 'http://127.0.0.1:5500'
  // ]}

));

app.delete('/cancelorder', (req, res) => {
  let oid = req.query.oid * 1;
  let sql = 'DELETE FROM orders where oid=?';
  pool.query(sql, [oid], (error, result) => {
    if (error) throw error;
    res.send({
      message: 'ok',
      code: 200
    });
  })
})

app.get('/getorder', (req, res) => {
  let uid = req.query.uid * 1;
  let sql = 'SELECT * FROM orders,house where uid=? and orders.hid=house.hid'
  pool.query(sql, [uid], (error, result) => {
    if (error) throw error;
    res.send({
      message: 'ok',
      code: 200,
      result: result
    });
  })
})

app.post('/order', (req, res) => {
  let order_phone = req.body.order_phone * 1;
  let order_name = req.body.order_name;
  let order_time = req.body.order_time;
  let uid = req.body.uid * 1;
  let hid = req.body.hid * 1;
  console.log(order_phone);
  let sql = 'INSERT orders(uid,order_name,order_time,order_phone,hid) VALUES(?,?,?,?,?)';
  pool.query(sql, [uid, order_name, order_time, order_phone, hid], (error, results) => {
    if (error) throw error;
    res.send({
      message: 'ok',
      code: 200
    });
  })
});

app.get('/house', (req, res) => {
  let sql = 'SELECT * FROM house ORDER BY hid';
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({
      message: 'ok',
      code: 200,
      results: results
    });
  });
});

app.post('/log/login', (req, res) => {
  //获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  let imgName = req.body.imgName;
  let captcha = req.body.captcha;
  let sql = 'SELECT picture_code from code WHERE tag=?'
  pool.query(sql, [imgName], (error, results) => {
    if (error) throw error;
    if (captcha == results[0].picture_code) {
      sql = 'SELECT * FROM user WHERE user_name=? AND upwd=?';
      pool.query(sql, [username, password], (error, results) => {
        if (error) throw error;
        if (results.length == 0) { //登录失败
          res.send({
            message: 'login failed',
            code: 201
          });
        } else { //登录成功
          res.send({
            message: 'ok',
            code: 200,
            result: results[0]
          });
        }
      });
    } else {
      res.send({
        message: '验证码错误',
        code: 202
      });
    }
  });
  // SQL语句

});

app.post('/reg/login', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  let email = req.body.email;
  let imgName = req.body.imgName;
  let captcha = req.body.captcha;
  //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT picture_code from code WHERE tag=?'
  pool.query(sql, [imgName], (error, results) => {
    if (error) throw error;
    if (captcha == results[0].picture_code) {
      sql = 'SELECT COUNT(uid) AS count FROM user WHERE user_name=?';
      pool.query(sql, [username], (error, results) => {
        if (error) throw error;
        let count = results[0].count;
        if (count == 0) {
          // 将用户的相关信息插入到数据表
          sql = 'INSERT user(user_name,upwd,email) VALUES(?,?,?)';
          pool.query(sql, [username, password, email], (error, results) => {
            if (error) throw error;
            res.send({
              message: 'ok',
              code: 200
            });
          })
        } else {
          res.send({
            message: '用户已存在',
            code: 201
          });
        }
      });
    } else {
      res.send({
        message: '验证码错误',
        code: 202
      });
    }
  });
});


// 获取城市列表的接口
// var cityJson = JSON.parse(fs.readFileSync("city.json"))
// console.log(cityJson)

// app.get("/getCity", (req, res) => {
//   res.send(cityJson)
// })

app.listen(3000, () => {
  console.log('app is running...');
});


// websockt 开始
var ws = require("nodejs-websocket");
var moment = require('moment');

console.log("开始建立连接...")

let users = [];
let conns = {};
let groups = [];

// 广播函数
function boardcast(obj) {
  if(obj.bridge && obj.bridge.length){
    obj.bridge.forEach(item=>{
      conns[item].sendText(JSON.stringify(obj));
      
    })
    return;
  }
  if (obj.groupId) {
    group = groups.filter(item=>{
      return item.id === obj.groupId
    })[0];
    group.users.forEach(item=>{
      conns[item.uid].sendText(JSON.stringify(obj));
    })
    return;
  }

  server.connections.forEach((conn, index) => {
      conn.sendText(JSON.stringify(obj));
  })
}

var server = ws.createServer(function(conn){
  conn.on("text", function (obj) {
    obj = JSON.parse(obj);
    conns[''+obj.uid+''] = conn;
    
    switch(obj.type){
      // 创建连接
      case 1:
        let isuser = users.some(item=>{
          return item.uid === obj.uid
        })
        if(!isuser){
          users.push({
            nickname: obj.nickname,
            uid: obj.uid,
            status: 1
          });
        } else {
          users.map((item, index)=>{
            if(item.uid === obj.uid){
              item.status = 1;
            }
            return item;
          })
        }
       
        break;
      // 注销
      case 2:
        // delete conns[''+obj.uid+''];
        users.map((item, index)=>{
          if(item.uid === obj.uid){
            item.status = 0;
          }
          return item;
        })
        // boardcast({
        //   type: 1,
        //   date: moment().format('YYYY-MM-DD HH:mm:ss'),
        //   msg: obj.nickname+'退出了聊天室',
        //   users: users,
        //   groups: groups,
        //   uid: obj.uid,
        //   nickname: obj.nickname,
        //   bridge: []
        // });
        break;
      // 创建群
      case 10:
        groups.push({
          id: moment().valueOf(),
          name: obj.groupName,
          users: [{
            uid: obj.uid,
            nickname: obj.nickname
          }]
        })
        boardcast({
          type: 1,
          date: moment().format('YYYY-MM-DD HH:mm:ss'),
          msg: obj.nickname+'创建了群' + obj.groupName,
          users: users,
          groups: groups,
          uid: obj.uid,
          nickname: obj.nickname,
          bridge: obj.bridge
        });
        break;
      // 加入群
      case 20:
        let group = groups.filter(item=>{
          return item.id === obj.groupId
        })[0]
        group.users.push({
          uid: obj.uid,
          nickname: obj.nickname
        })
        boardcast({
          type: 1,
          date: moment().format('YYYY-MM-DD HH:mm:ss'),
          msg: obj.nickname+'加入了群' + obj.groupName,
          users: users,
          groups: groups,
          uid: obj.uid,
          nickname: obj.nickname,
          bridge: obj.bridge
        });
        break;
      // 发送消息
      default:
        boardcast({
          type: 2,
          date: moment().format('YYYY-MM-DD HH:mm:ss'),
          msg: obj.msg,
          uid: obj.uid,
          nickname: obj.nickname,
          bridge: obj.bridge,
          groupId: obj.groupId,
          status: 1
        });
        break;
    }
  })
  conn.on("close", function (code, reason) {
    console.log("关闭连接")
  });
  conn.on("error", function (code, reason) {
    console.log("异常关闭")
  });
}).listen(8001)
console.log("WebSocket建立完毕")